const db = require('../db/index')
const Book = require('../modules/Book')
const _ = require('lodash')

function exists(book){
    const {title,author,publisher} = book
    const sql = `select * from book where title='${title}' and author='${author}' and publisher='${publisher}'`
    return db.queryOne(sql)
}

function removeBook(book){
    if(book){
        book.reset()
    }
}

async function insertContents(book){
    const contents = book.getContents()
    if(contents && contents.length>0){
        for(let i=0;i<contents.length;i++){
            const content = contents[i]
            const _content = _.pick(content,[
                'filename',
                'id',
                'href',
                'order',
                'text',
                'level',
                'label',
                'pid',
                'navId'
            ])

            await db.insert(_content,'contents')
        }
        
    }
}

function insertBook(book){
    return new Promise(async(resolve,reject)=>{
        try{
            if(book instanceof Book){

                const result = await exists(book)
                if(result){
                    await removeBook(book)
                    reject(new Error('电子书已存在'))
                }else{
                    await db.insert(book.toDb(),'Book').then().catch(e=>{
                        reject(e)
                    })
                    await insertContents(book)
                    resolve()
                }
            }else{
                reject(new Error('您添加的图书不合法'))
            }
        }catch(e){
            reject(e)
        }
    })
}

function getBook(filename){
    return new Promise(async (resolve,reject)=>{
        const bookSql = `select * from book where fileName='${filename}'`
        const contentsSql = `select * from contents where fileName='${filename}' ORDER BY \`order\``
        const book = await db.queryOne(bookSql)
        const contents = await db.querySelect(contentsSql)
        if(book){
            book.cover = Book.genCoverUrl(book)
            book.contentsTree = Book.genContentsTree(contents)
            resolve({book})
        }else{
            reject(new Error('电子书不存在'))
        }
        
    })
}

function updateBook(book){
    return new Promise(async (resolve,reject)=>{
        try{
            if(book instanceof Book){

                const model = book.toDb()
                const result = await getBook(book.fileName)

                if(result){
                    
                    if(+result.updateType === 0){
                        reject(new Error('内置图书不能编辑'))
                    }else{
                        await db.update(model,'book',`where \`fileName\`='${book.fileName}'`)
                        resolve()
                    }
                }

            }else{
                reject(new Error('更新的图书对象不合法'))
            }
        }catch(e){
            reject(e)
        }

    })
}

async function getCategory(){
    const sql = 'select * from category order by category asc'
    const result = await db.querySelect(sql)
    const categoryList = []
    console.log(result)
    result.forEach(item=>{
       categoryList.push({
           label:item.categoryText,
           value:item.category,
           num:item.num
       })
   })
   return categoryList
}

async function listBook(query){
    console.log(query)
    const {category,author,title,page=1,pageSize=20,sort} = query
    const offset = (page-1)*pageSize
    let bookSql = 'select * from book'
    let where = 'where'
    category && db.and(where,'category',category)
    title && (where = db.andLike(where,'title',title))
    author && (where =  db.andLike(where,'author',author))
    if(where!=='where'){
        bookSql = `${bookSql} ${where}`
    }
    if(sort){
        const symbol = sort[0]
        const column = sort.slice(1,sort.length)
        const order = symbol === '+' ? 'asc' : 'desc'
        bookSql = `${bookSql} order by \`${column}\` ${order}`
    }
    let countSql = `select count(*) as count from book`
    if(where!=='where')
    {
        countSql = `${countSql} ${where}`
    }
    const count = await db.querySelect(countSql)
    console.log('count:'+JSON.stringify(count))
    bookSql = `${bookSql} limit ${pageSize} offset ${offset}`
    const list = await db.querySelect(bookSql)
    return {list,count:count[0].count,page:+page,pageSize:+pageSize}
}

function deleteBook(fileName){
    return new Promise(async (resolve,reject)=>{
        let {book} = await getBook(fileName)
        if(book){
            if(+book.updateType===0){
                reject(new Error('内置电子书不能删除'))
            }else{
                const bookObj = new Book(null,book)
                const sql = `delete from book where fileName='${fileName}'`
                db.querySelect(sql).then(()=>{
                    bookObj.reset()
                    resolve
                })
            }
        }else{
            reject(new Error('电子书不存在'))
        }
    })
}

module.exports = {
    insertBook,
    getBook,
    updateBook,
    getCategory,
    listBook,
    deleteBook
}